package com.vincce.sport.controller;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.vincce.sport.core.utils.CheckUtil;
import com.vincce.sport.core.utils.ConvertUtil;
import com.vincce.sport.entity.Page;
import com.vincce.sport.entity.SysRole;
import com.vincce.sport.entity.SysUser;
import com.vincce.sport.entity.SysUserRole;
import com.vincce.sport.entity.Team;
import com.vincce.sport.mapper.SysRoleMapper;
import com.vincce.sport.mapper.SysUserMapper;
import com.vincce.sport.mapper.TeamMapper;

@Controller
@RequestMapping("/sysUser")
public class SysUserController extends BaseController{

	@Resource
	private SysUserMapper sysUserMapper;
	
	@Resource
	private SysRoleMapper sysRoleMapper;
	
	@Resource
	private TeamMapper teamMapper;
	
    @RequestMapping("/list")
    public String sysUserList(Model model, SysUser sysUser, Page<SysUser> page) throws IOException{
        Map<String, Object> filter = new HashMap<String, Object>();
        if(sysUser.getUserName() != null && !sysUser.getUserName().equals("")){
            filter.put("userName", sysUser.getUserName());
        }
        if(sysUser.getUserStatus() != null && !sysUser.getUserStatus().equals("")){
            filter.put("userStatus", sysUser.getUserStatus());
        }
        page.setFilter(filter);
        
        page.setResult(sysUserMapper.querySysUserList(page));
        page.setTotal(sysUserMapper.querySysUserCount(page.getFilter()));
        model.addAttribute("page",page);

        List<SysRole> sysRoleList = sysRoleMapper.findAllSysRole();
        model.addAttribute("sysRoleList",sysRoleList);
        
        List<Team> teamList = teamMapper.queryTeamByAll();
        model.addAttribute("teamList",teamList);
        
        return "backstage/sysUserList";
    }

    @RequestMapping("/addOrUpdate")
    @ResponseBody
    public String addOrUpdateSysUser(Model model, SysUser sysUser, HttpServletRequest request) throws IOException{
    	Long count = 0l;
        //密码md5加密
        if(sysUser.getPassword()!=null && !"".equals(sysUser.getPassword())){
        	try {
				sysUser.setPassword(ConvertUtil.encryptMD5(sysUser.getPassword()));
			} catch (Exception e) {
				e.printStackTrace();
			}
        }
        
        //更新人和更新时间
        sysUser.setUpdateUser(getCurrentUser().getId().intValue());
        sysUser.setUpdateTime(new Date());
        if(CheckUtil.isEmpty(sysUser.getId())){
        	//创建 人和创建时间
        	sysUser.setCreateUser(getCurrentUser().getId().intValue());
            sysUser.setCreateTime(new Date());

            count = sysUserMapper.insertSysUser(sysUser);
        } else{
        	count = sysUserMapper.updateSysUser(sysUser);
        }
        
        if(count > 0){
			SysUserRole sysUserRole = new SysUserRole();
			sysUserRole.setUserId(sysUser.getId().intValue());
			sysUserRole = findSysUserRole(sysUserRole);
			if(sysUserRole == null){
				sysUserRole = new SysUserRole();
				sysUserRole.setRoleId(sysUser.getRoleId());
				sysUserRole.setUserId(sysUser.getId().intValue());
				count = changeSysUserRole(sysUserRole);
			} else{
				if(sysUser.getRoleId() != sysUserRole.getRoleId()){
					sysUserRole.setRoleId(sysUser.getRoleId());
					count = changeSysUserRole(sysUserRole);
				}
			}
			
		}

        this.sessionPutNodeResource(request);        //加载侧边条资源
        this.sessionPutResource(request);	//角色资源与全部资源放入session
        
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("suc", count > 0 ? true : false);
        return JSON.toJSONString(result);
    }

    @RequestMapping("/delete")
    @ResponseBody
    public String deleteSysUser(Model model,SysUser sysUser, Long id, HttpServletRequest request) throws IOException{
        boolean flag=false;

        sysUserMapper.deleteById(id);
        
        this.sessionPutNodeResource(request);        //加载侧边条资源
        this.sessionPutResource(request);	//角色资源与全部资源放入session

        flag = true;
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("obj", flag);
        return JSON.toJSONString(result);
    }

    /**
     * 檢查用户是否已存在
     * @param loginName
     * @param id
     * @return
     * @throws Exception
     */
    @RequestMapping("/checkLoginName")
    @ResponseBody
    public String checkRoleName(String loginName,Long id) throws Exception
    {
        SysUser sysUser=new SysUser();
        if(loginName != null && !loginName.equals("")){
            sysUser.setLoginName(loginName);
        }
        if(id!= null && !id.equals("")){
            sysUser.setId(id);
        }
        
        Integer fg = 0;
        List<SysUser> sysUserList = sysUserMapper.findSysUserByOne(sysUser);
        if(sysUserList!=null && sysUserList.size()>0){
        	fg = 1;
        }
        return Boolean.toString(fg==0);
    }
    
	/**
	 * 查询用户角色关联
	 * @param sysUserRole
	 * @return
	 */
	public SysUserRole findSysUserRole(SysUserRole sysUserRole){
		List<SysUserRole> sysUserRolesList = sysUserMapper.findSysUserRole(sysUserRole);
		if(sysUserRolesList!=null && sysUserRolesList.size()>0){
			if(sysUserRolesList.size()>1){
				for(SysUserRole syr:sysUserRolesList){
					sysUserMapper.deleteSysUserRoleById(syr.getId());
				}
			} else{
				return sysUserRolesList.get(0);
			}
		}
		return null;
	}
	
	/**
	 * 改变用户角色关联
	 * @param sysUserRole
	 * @return
	 */
	public Long changeSysUserRole(SysUserRole sysUserRole){
		Long flag;
		if(sysUserRole.getId() != null){
			flag = sysUserMapper.updateSysUserRole(sysUserRole);
		} else{
			flag = sysUserMapper.insertSysUserRole(sysUserRole);
		}
		
		return flag;
	}

}
